package com.gitee.linmt.controller;

import com.gitee.linmt.base.PostParam;
import com.gitee.linmt.entity.Result;
import com.gitee.linmt.entity.SysUser;
import com.gitee.linmt.exception.ServiceException;
import com.gitee.linmt.service.SysUserService;
import com.gitee.linmt.util.SpringSecurityUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户 Controller.
 *
 * @author <a href="mailto:lin-mt@outlook.com">lin-mt</a>
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    
    private final SysUserService sysUserService;
    
    public SysUserController(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }
    
    /**
     * 用户注册.
     *
     * @param postParam :save 用户信息
     * @return 注册后的用户信息
     */
    @PostMapping("/register")
    public Result<SysUser> register(@RequestBody SysUserPostParam postParam) {
        // TODO 可以根据租户的配置确定是否注册就直接启用该用户
        postParam.getSave().setEnabled(1);
        return Result.success(sysUserService.save(postParam.getSave()));
    }
    
    /**
     * 删除用户.
     *
     * @param postParam :deleteId 要删除的用户ID
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public Result<Object> delete(@RequestBody SysUserPostParam postParam) {
        if (sysUserService.delete(postParam.getDeleteId())) {
            return Result.deleteSuccess();
        }
        return Result.deleteFailure();
    }
    
    /**
     * 更新用户.
     *
     * @param postParam :update 要更新的用户信息
     * @return 更新后的用户信息
     */
    @PutMapping("/update")
    public Result<SysUser> update(@RequestBody SysUserPostParam postParam) {
        return Result.success(sysUserService.update(postParam.getUpdate()));
    }
    
    /**
     * 获取当前登陆人信息.
     *
     * @return 当前登陆人信息
     */
    @GetMapping("/currentUserInfo")
    public Result<SysUser> currentUserInfo() {
        return Result.success(SpringSecurityUtils.getCurrentUser());
    }
    
    static class SysUserPostParam extends PostParam<SysUser> {
        
        @Override
        public void checkProperties(SysUser entity) {
            if (entity.getUsername() == null) {
                throw new ServiceException("E0001");
            }
            if (entity.getSecretCode() == null) {
                throw new ServiceException("E0002");
            }
        }
    }
}
